import { login, getUserInfo, getUserDetailById } from '@/api'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    // 修改token
    SET_TOKEN(state, token) {
      state.token = token
      setToken(token)
    },
    SET_USERINFO(state, userInfo) {
      state.userInfo = userInfo
    },
    REMOVE_TOKEN(state) {
      state.token = ''
      removeToken()
      resetRouter()
    }
  },
  actions: {
    async fetchLogin(store, loginForm) {
      const { data } = await login(loginForm)
      store.commit('SET_TOKEN', data)
      return data
    },
    async fetchUserInfo(store) {
      const res = await getUserInfo()
      const res1 = await getUserDetailById(res.data.userId)
      store.commit('SET_USERINFO', { ...res.data, ...res1.data })
      return res.data.roles
    }
  }
}
